const express = require('express');
const cors = require('cors');
const mysql = require('mysql2');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 设置全局JWT密钥
global.JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key_change_this_in_production';

// 中间件
app.use(cors());
app.use(express.json());

// 数据库连接
const db = mysql.createConnection({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '123456',
  database: process.env.DB_NAME || 'store_db'
});

// 连接数据库
db.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('数据库连接成功');
});

// 将数据库连接设为全局变量
global.db = db;

// 路由
app.use('/api/auth', require('./routes/auth'));
app.use('/api/address', require('./routes/address'));
app.use('/api/coupon', require('./routes/coupon'));
app.use('/api/order', require('./routes/order'));
app.use('/api/user', require('./routes/user'));
app.use('/api/favorite', require('./routes/favorite'));
app.use('/api/customer-service', require('./routes/customer-service'));
app.use('/api/cart', require('./routes/cart'));

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
  console.log(`本地访问: http://localhost:${PORT}`);
  console.log(`模拟器访问: http://10.0.2.2:${PORT}`);
  console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
});





